package gui;

import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JLabel;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;

import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ConnectedGUI extends JFrame implements ListSelectionListener{
	
	private P2PGUI gui;
	
	private String filepath;
	private boolean fileSelected;
	
	
	private static JList list;
    final static DefaultListModel modelListUser=new DefaultListModel();

    private JTextArea list_messages;

	private JTextArea textArea;
	private JTextArea textArea_1;
    private JTextArea fileArea;
	
	
    private User remoteUser;
	private JLabel lblHistory;
	public ConnectedGUI(P2PGUI gui) {
		super();
		
		this.gui = gui;
		fileSelected = false;
		init();
	}
		
	

		public void init(){
		setTitle("Chat_INSA");
		getContentPane().setLayout(null);
		
		this.setSize(665,600);
		
		JLabel lblConnectedUsers = new JLabel("Connected Users");
		lblConnectedUsers.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblConnectedUsers.setBounds(9, 48, 114, 14);
		getContentPane().add(lblConnectedUsers);
		
		JLabel lblWrite = new JLabel("Your message");
		lblWrite.setBounds(163, 342, 94, 14);
		getContentPane().add(lblWrite);
		
		
		JScrollPane scrollPane_MessageToSend = new JScrollPane();
		scrollPane_MessageToSend.setBounds(133, 357, 266, 68);
		getContentPane().add(scrollPane_MessageToSend);
		textArea = new JTextArea();
		scrollPane_MessageToSend.setViewportView(textArea);
		
		JScrollPane scrollPane_fileToSend = new JScrollPane();
		scrollPane_fileToSend.setBounds(133, 425, 266, 68);
		getContentPane().add(scrollPane_fileToSend);
		fileArea = new JTextArea();
		scrollPane_fileToSend.setViewportView(fileArea);
		fileArea.setEditable(false);

		
		JButton btnAnswer = new JButton("SEND");
		btnAnswer.setBounds(238, 515, 89, 40);
		btnAnswer.setFont(new Font("Tahoma", Font.PLAIN, 17));
		getContentPane().add(btnAnswer);
		btnAnswer.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				String messageToSend = textArea.getText();
				Object[] users = list.getSelectedValues();
				if(!(users.length == 0)){
					for(Object user : users){
						if(!(messageToSend.equals(""))){

						ConnectedGUI.this.gui.sendMessage(messageToSend, (User) user);
						}
						if(fileSelected){
							gui.sendFile(filepath, (User) user);
						}
					}
					textArea.setText("");
					fileArea.setText("");
					fileSelected = false;
					}
				else{
					JOptionPane.showMessageDialog(null,  "No user selected");
				}
			}
		});
		
		JButton btnDisconnect = new JButton("Disconnect");
		btnDisconnect.setFont(new Font("Tahoma", Font.PLAIN, 17));
		btnDisconnect.setBounds(493, 11, 135, 41);
		getContentPane().add(btnDisconnect);
		btnDisconnect.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				ConnectedGUI.this.gui.disconnectGUI();
				System.exit(EXIT_ON_CLOSE);
			}
		});
		
		
		JLabel lblConversation = new JLabel("Conversation");
		lblConversation.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblConversation.setBounds(146, 26, 94, 14);
		getContentPane().add(lblConversation);
		
		JScrollPane scrollPane_Conversation = new JScrollPane();
		scrollPane_Conversation.setBounds(133, 47, 280, 294);
		getContentPane().add(scrollPane_Conversation);
		
		list_messages = new JTextArea();
		scrollPane_Conversation.setViewportView(list_messages);
		list_messages.setEditable(false); 
		
		JScrollPane scrollPane_history = new JScrollPane();
		scrollPane_history.setBounds(414, 107, 235, 316);
		getContentPane().add(scrollPane_history);
		
		textArea_1 = new JTextArea();
		textArea_1.setBackground(new Color(51, 204, 255));
		scrollPane_history.setViewportView(textArea_1);
		textArea_1.setEditable(false);
		
		JLabel lblHistory = new JLabel("History");
		lblHistory.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblHistory.setBounds(479, 73, 58, 29);
		getContentPane().add(lblHistory);


		list = new JList(modelListUser);
		list.addListSelectionListener(this);
        JScrollPane scrollList = new JScrollPane(list);
        scrollList.setBounds(0, 73, 127, 322);
        getContentPane().add(scrollList);
		
        JButton btnSelectFile = new JButton("Select File");
		btnSelectFile.setFont(new Font("Tahoma", Font.PLAIN, 12));
		btnSelectFile.setBounds(145, 498, 130, 15);
		getContentPane().add(btnSelectFile);
		btnSelectFile.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				ConnectedGUI.this.gui.selectFile();
			}
		});
        
		
		
		JButton btnRemoveFile = new JButton("RemoveFile");
		btnRemoveFile.setFont(new Font("Tahoma", Font.PLAIN, 12));
		btnRemoveFile.setBounds(273, 498, 130, 15);
		getContentPane().add(btnRemoveFile);
		btnRemoveFile.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				ConnectedGUI.this.setFileSelected(false);
				fileArea.setText("");
			}
		});
        
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //TODO
	}

		
		public void justConnected(String hostname) {
            // si l'utilisateur n'est pas l'utilisateur local, on affiche le message
            //if (!gui.getModelListUser().getLocalUser().getName().equals(hostname))
			if(!(modelListUser.getSize() == 1)){
            JOptionPane.showMessageDialog(this,hostname+" is connected.");
			}
    }
   
    public void justDisconnected(String hostname) {
            JOptionPane.showMessageDialog(this,hostname+" is disconnected.");
    }

	@Override
	public void valueChanged(ListSelectionEvent arg0) {
		this.remoteUser = (User) list.getSelectedValue();	
	}


	public void addToList(User user) {
		this.modelListUser.addElement(user);
		this.getList().repaint();
		this.justConnected(user.getName());
		System.out.println(this.modelListUser.toString());
	}
	
	public void removeFromList(InetAddress ip) {
		Enumeration<User> enumeration = (Enumeration<User>) modelListUser.elements();
		while(enumeration.hasMoreElements()){
		User user = enumeration.nextElement();
    	//enumeration.nextElement().getIpAddress().equals(ip);
    	if(user.getIpAddress().equals(ip)){
    	this.modelListUser.removeElement(user);
    	this.justDisconnected(user.getName());
    	}
    	}
		
		this.getList().repaint();
		System.out.println(this.modelListUser.toString());
	}
	
	public static User get_user_by_ip (String ip) throws UnknownHostException{
		User good_user = null;
		Enumeration<User> enumeration = (Enumeration<User>) modelListUser.elements();
		while(enumeration.hasMoreElements()){
		User user = enumeration.nextElement();
    	if(user.getIpAddress().equals(InetAddress.getByName(ip))){
		good_user = user;
    	}
		}
    	return good_user;
	}
	
	public void updateListMessages(String ip, String message) throws UnknownHostException{
		Enumeration<User> enumeration = (Enumeration<User>) modelListUser.elements();
		while(enumeration.hasMoreElements()){
		User user = enumeration.nextElement();
    	if(user.getIpAddress().equals(InetAddress.getByName(ip))){
		this.list_messages.append("From User " + user.getName() + " : " + message + "\n");
    	}
		}
	}
	
	public void updateListMessages(String messageToSend, User remoteUser2) {
		this.list_messages.append("You to " + remoteUser2.getName() + " : " + messageToSend + "\n");		
	}

	public void updateListMessages(String fileText){
		this.list_messages.append(fileText);
	}
	
	public void updateHistory(String text) {
		this.textArea_1.append(text + " \n");		
	}
	// GETTERS & SETTERS
	
    public DefaultListModel getModelListUser() {
		return modelListUser;
	}

	public static JList getList() {
		return list;
	}

	public User getRemoteUser() {
		return remoteUser;
	}

	
	public boolean isFileSelected() {
		return fileSelected;
	}

	public void setFileSelected(boolean fileSelected) {
		this.fileSelected = fileSelected;
	}
	

    public void writeInFileArea(String messageToWrite){
    	this.fileArea.append(messageToWrite);
    }

	public String getFilepath() {
		return filepath;
	}
	public void setFilepath(String filepath) {
		this.filepath = filepath;
	}
}
